<template>
    <div class="divClass">
        <Form ref="formItem" :model="formItem" :rules="ruleForm" label-width="120">
            <Card :bordered="false" :dis-hover="true">
                <p slot="title" style="height:35px;margin-top:5px">
                    <label>请搜索患者信息：</label>
                    <AutoComplete
                        clearable
                        v-model="formItem.patientName"
                        icon="ios-search"
                        placeholder="姓名 / 手机 / 病历号"
                        style="width:250px"
                        @on-select="selectOption"
                        @keyup.enter.native="search">
                        <div>
                            <Option v-if="patients.length === 0" :value="-1" :key="-1">
                                <span class="demo-auto-complete-title">暂无结果</span>
                            </Option>
                            <Option v-for="item in patients" :value="item.id" :key="item.id">
                                <Row>
                                    <Col span="12">
                                        <span class="demo-auto-complete-title">{{ item.name }}</span>
                                    </Col>
                                    <Col span="12">
                                        <span class="demo-auto-complete-count">{{ item.medicalId }}</span>
                                    </Col>
                                </Row>
                            </Option>
                        </div>
                    </AutoComplete>
                </p>
                <Card :bordered="false" :dis-hover="true">
                    <Row style="font-size: 16px; font-weight: bold;">
                        <Col :span="5" :offset="1">病历号：<a href="#">{{patient.medicalId}}</a></Col>
                        <Col :span="6">患者姓名：<a href="#">{{patient.name}}</a></Col>
                        <Col :span="6">患者昵称：<a href="#">{{patient.nickName}}</a></Col>
                        <Col :span="6">患者性别：<a href="#">{{patient.sex | sexFilter}}</a></Col>
                    </Row>
                    <br/>
                    <Row style="font-size: 16px; font-weight: bold;">
                        <Col :span="5" :offset="1">手机号码：<a href="#">{{patient.phone}}</a></Col>
                        <Col :span="6">出生日期：<a href="#">{{patient.birthday}}</a></Col>
                        <Col :span="6">微信号码：<a href="#">{{patient.wechat}}</a></Col>
                        <Col :span="6">现住址：<a href="#">{{patient.address}}</a></Col>
                    </Row>
                </Card>
            </Card>
            <Row>
                <Col span="24">
                    <Card :bordered="false" :dis-hover="true">
                        <p slot="title">
                            请填写预约信息：
                        </p>
                        <Row>
                            <Col span="6">
                                <FormItem label="问题描述：">
                                    <Input v-model="formItem.description" type="textarea" :autosize="{minRows: 4,maxRows: 5}" placeholder="请输入内容..."></Input>
                                </FormItem>
                            </Col>
                            <Col span="6">
                                <FormItem label="可能诊断：">
                                    <Input v-model="formItem.diagnosis" type="textarea" :autosize="{minRows: 4,maxRows: 5}" placeholder="请输入内容..."></Input>
                                </FormItem>
                            </Col>
                            <Col span="6">
                                <FormItem label="承诺备注：">
                                    <Input v-model="formItem.promise" type="textarea" :autosize="{minRows: 4,maxRows: 5}" placeholder="请输入内容..."></Input>
                                </FormItem>
                            </Col>
                            <Col span="6">
                                <FormItem label="预约备注：">
                                    <Input v-model="formItem.note" type="textarea" :autosize="{minRows: 4,maxRows: 5}" placeholder="请输入内容..."></Input>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row>
                            <Col span="6">
                                <FormItem label="预约类型：" prop="type">
                                    <Select v-model="formItem.type" clearable>
                                        <Option value="1">复诊</Option>
                                        <Option value="2">新诊</Option>
                                    </Select>
                                </FormItem>
                            </Col>
                            <Col span="6">
                                <FormItem label="处理方式：" prop="process">
                                    <Select v-model="formItem.process" clearable>
                                        <Option value="1">电话随访</Option>
                                        <Option value="2">预约到店</Option>
                                    </Select>
                                </FormItem>
                            </Col>
                            <Col span="6">
                                <FormItem label="提醒方式：" prop="remind">
                                    <Select v-model="formItem.remind" clearable>
                                        <Option value="1">短信</Option>
                                        <Option value="2">微信</Option>
                                        <Option value="3">电话</Option>
                                    </Select>
                                </FormItem>
                            </Col>
                            <Col span="6">
                                <FormItem label="预约时间：">
                                    <!--<DatePicker @on-change="changeAppointment" v-model="formItem.appointment" format="yyyy-MM-dd HH:mm" type="datetimerange" :time-picker-options="{steps: [2, 10]}" placeholder="请选择时间..." style="width: 100%"></DatePicker>-->
                                    <Row>
                                        <Col span="11">
                                            <DatePicker style="width: 100%" @on-change="changeDate" format="yyyy-MM-dd" type="date" placeholder="请选择日期"></DatePicker>
                                        </Col>
                                        <Col span="2" align="center">-</Col>
                                        <Col span="11">
                                            <TimePicker style="width: 100%" @on-change="changeTime" format="HH:mm" :disabled-hours="[0,1,2,3,4,5,6,7,8,9]" placeholder="请选择时间"></TimePicker>
                                        </Col>
                                    </Row>
                                </FormItem>
                            </Col>
                        </Row>
                    </Card>
                </Col>
            </Row>
            <Row>
                <Col span="24">
                    <Card :bordered="false" :dis-hover="true">
                        <p slot="title">
                            请选择预约医生：
                        </p>
                        <FormItem prop="doctorId">
                            <RadioGroup size="large" v-model="formItem.doctorName">
                                <Radio v-for="item in healthcare" v-if="item.job === 1" :value="item.id" :label="item.username" @click.native="changeDoctor(item)"></Radio>
                            </RadioGroup>
                        </FormItem>
                    </Card>
                </Col>
            </Row>
            <Row>
                <Col span="24">
                    <Card :bordered="false" :dis-hover="true">
                        <p slot="title">
                            请选择预约护士：
                        </p>
                        <FormItem prop="nurseId">
                            <RadioGroup size="large" v-model="formItem.nurseName">
                                <Radio v-for="item in healthcare" v-if="item.job === 2" :value="item.id" :label="item.username" @click.native="changeNurse(item)"></Radio>
                            </RadioGroup>
                        </FormItem>
                    </Card>
                </Col>
            </Row>
            <Row>
                <Col span="24">
                    <Card :bordered="false" :dis-hover="true">
                        <p slot="title" style="height: 40px">&nbsp;</p>
                        <Table @on-selection-change="selectChange" :data="data" :columns="dataModel.columns" size="small" ref="table"></Table>
                    </Card>
                </Col>
            </Row>
            <Card :bordered="false" :dis-hover="true">
                <p align="right">
                    <Button @click="add" type="success" size="large">添加</Button>
                    <Button @click="remove" type="error" size="large">移除</Button>
                    <Button @click="submit" type="primary" size="large" icon="android-checkmark-circle">提交</Button>
                </p>
            </Card>
        </Form>
    </div>
</template>

<script>
import iviewTable from '@/view/common/table/Table.vue';
import iviewPage from '@/view/common/page/Page.vue';
export default {
    components: {
        iviewTable,
        iviewPage
    },
    data () {
        return {
            // 考勤
            attendanceURL: '/user/attendance',
            // 预约
            reservationURL: '/user/reservation',
            selectRows: [],
            showTag: false,
            reAppointmentFlag: false,
            patients: [],
            patient: {},
            panelName: '',
            healthcare: [],
            data: [],
            appointmentDate: '',
            appointmentTime: '',
            // 预约信息
            formItem: {
                patientId: '',
                patientName: '',
                type: '',
                description: '',
                diagnosis: '',
                promise: '',
                remind: '',
                process: '',
                doctorId: '',
                doctorName: '',
                nurseId: '',
                nurseName: '',
                appointment: '',
                appointmentStr: '',
                note: '',
                index: ''
            },
            ruleForm: {
                type: [
                    { required: true, message: '请选择预约类型', trigger: 'change' }
                ],
                remind: [
                    { required: true, message: '请选择提醒方式', trigger: 'change' }
                ],
                process: [
                    { required: true, message: '请选择处理方式', trigger: 'change' }
                ],
                doctorName: [
                    { required: true, message: '请选择预约医生', trigger: 'change' }
                ],
                nurseName: [
                    { required: true, message: '请选择预约护士', trigger: 'change' }
                ]
            },
            // 查询模型
            queryModel: {
                // 网关代理路径(必须)+资源路径(可选)
                baseURL: '/user/patient',
                searchValue: ''
            },
            // 数据模型
            dataModel: {
                menuId: 101,
                columns: [
                    {
                        type: 'selection',
                        width: 60,
                        align: 'center',
                    },
                    {
                        title: '预约类型',
                        key: 'type',
                        render: (h, params) => {
                            let temp = params.row.type
                            if (temp === '1') {
                                temp = '复诊'
                            } else if (temp === '2') {
                                temp = '新诊'
                            }
                            return temp
                        }
                    },
                    {
                        title: '提醒方式',
                        key: 'remind',
                        render: (h, params) => {
                            let temp = params.row.type
                            if (temp === '1') {
                                temp = '短信'
                            } else if (temp === '2') {
                                temp = '微信'
                            } else if (temp === '3') {
                                temp = '电话'
                            }
                            return temp
                        }
                    },
                    {
                        title: '处理方式',
                        key: 'process',
                        render: (h, params) => {
                            let temp = params.row.process
                            if (temp === '1') {
                                temp = '电话随访'
                            } else if (temp === '2') {
                                temp = '预约到店'
                            }
                            return temp
                        }
                    },
                    {
                        title: '预约时间',
                        key: 'appointmentStr',
                    },
                    {
                        title: '预约医生',
                        key: 'doctorName',
                    },
                    {
                        title: '预约护士',
                        key: 'nurseName',
                    }
                ],
                order: 'creation_time desc'
            }
        }
    },
    filters: {
        nameFilter (value) {
            let temp = ''
            if (!value) {
                temp = '请选择患者'
            } else {
                temp += value + ' - 基本资料'
            }
            return temp
        },
        sexFilter (value) {
            let temp = ''
            if (value === 1) {
                temp = '男'
            } else if (value === 2) {
                temp = '女'
            }
            return temp
        }
    },
    methods: {
        // 调用后台查询
        search () {
            let url = 'user/patient/search'
            this.$ajax.post(url, this.addFilter(this.formItem.patientName, 'name', 'phone', 'medical_number')).then(function (response) {
              let {code, data} = response.data
              if (code === 0) {
                if (data.length === 1) {
                    this.patient = data[0]
                    this.formItem.patientId = data[0].id
                } else {
                    this.patients = data
                }
              }
            }.bind(this))
        },
        addFilter (val, ...fields) {
            let queryModel = {
                mode: 'or',
                pageNumber: 1,
                pageSize: 10,
                order: 'id',
                filters: []
            }
            for (let field of fields) {
                let filterModel = {'field': field, 'value1': val, 'operate': 'LIKE'}
                queryModel.filters.push(filterModel)
            }
            return queryModel
        },
        selectOption (value) {
            if (value) {
                let url = '/user/patient/findById/' + value
                this.$ajax.get(url).then((response) => {
                    let {code, data} = response.data
                    if (code === 0) {
                        this.showTag = true
                        this.patient = data
                        this.formItem.patientId = value
                        this.formItem.patientName = data.name
                        this.panelName = "patient"
                    }
                })
            } else {
                this.showTag = false
                this.patient = {}
                this.panelName = ""
            }
        },
        changeDate (val, type) {
            this.appointmentDate = val
        },
        changeTime (val) {
            this.appointmentTime = val
        },
        changeAppointment (val) {
            if (val !== '') {
                if (this.formItem.type === '') {
                    this.$bus.alert('warning', '请先选择预约类型')
                    return
                }
                if (this.formItem.process === '') {
                    this.$bus.alert('warning', '请先选择处理方式')
                    return
                }
                // 清空已选的医护
                this.formItem.doctorId = ''
                this.formItem.doctorName = ''
                this.formItem.nurseId = ''
                this.formItem.nurseName = ''
                this.formItem.appointmentStr = val
                let url = this.attendanceURL + '/getHealthcare/' + val + ':00/' + this.formItem.type + '/' + this.formItem.process
                this.$ajax.get(url).then((response) => {
                    let {code, data, msg} = response.data
                    if (code === 0) {
                        this.healthcare = data
                        this.formItem.appointmentStr = val + ':00'
                    } else {
                        this.$bus.alert('error', msg)
                    }
                })
            }else{
                this.healthcare = []
            }
        },
        // 添加至预约列表
        add () {
            if (this.formItem.patientId !== '') {
                this.$refs['formItem'].validate((valid) => {
                    if (valid) {
                        this.formItem.index = this.data.length
                        this.data.push(Object.assign({}, this.formItem))
                    }
                })
            } else {
                this.$bus.alert('warning', '请选择预约患者')
            }
        },
        // 从预约列表中移除
        remove () {
            let rows = this.selectRows
            if (rows.length > 0) {
                for (let row of rows) {
                    this.data.splice(this.data.findIndex(item => item.index === row.index), 1)
                }
            } else {
                this.$bus.alert('warning', '请选择列表中的数据')
            }
        },
        submit () {
            if (this.reAppointmentFlag) {
                if (this.data.length === 1) {
                    this.$Modal.confirm({
                        title: '操作提示',
                        content: '<p>确认重新预约?</p>',
                        onOk: () => {
                            let url = this.reservationURL + '/change'
                            this.$ajax.post(url, this.data[0]).then((response) => {
                                let {code, msg} = response.data
                                if (code === 0) {
                                    this.$bus.alert('success', '预约成功')
                                    this.$bus.init(this.formItem, ['patientId', 'patientName'])
                                    this.reset()
                                    this.data = []
                                    this.reAppointmentFlag = false
                                } else {
                                    this.$bus.modal('error', '系统提示', msg)
                                }
                            })
                        }
                    })
                } else {
                    this.$bus.modal('warning', '系统提示', '请添加一条预约')
                }
            } else {
                if (this.data.length > 0) {
                    this.$Modal.confirm({
                        title: '操作提示',
                        content: '<p>确认预约?</p>',
                        onOk: () => {
                            let url = this.reservationURL + '/saveAppointment'
                            this.$ajax.post(url, this.data).then((response) => {
                                let {code, msg} = response.data
                                if (code === 0) {
                                    this.$bus.alert('success', '预约成功')
                                    this.$bus.init(this.formItem, ['patientId', 'patientName'])
                                    this.reset()
                                    this.data = []
                                } else {
                                    this.$bus.modal('error', '系统提示', msg)
                                }
                            })
                        }
                    })
                } else {
                    this.$bus.alert('warning', '请至少添加一条预约')
                }
            }
        },
        // 变更医生
        changeDoctor (user) {
            this.formItem.doctorId = user.id
        },
        // 变更护士
        changeNurse (user) {
            this.formItem.nurseId = user.id
        },
        selectChange (selection) {
            this.selectRows = selection
        },
        reset () {
            this.$refs.formItem.resetFields()
        },
        init () {
            this.$bus.init(this.formItem)
            this.reAppointmentFlag = false
            if (this.$route.query.id) {
                let row = this.$route.query
                this.formItem = row
                this.formItem.type = row.type + ''
                this.formItem.remind = row.remind + ''
                this.formItem.process = row.process + ''
                this.formItem.appointment = ''
                this.formItem.note = ''
                this.search()
                this.reAppointmentFlag = true
            }
        }
    },
    mounted () {
        this.init()
    },
    watch: {
        '$route' (to) {
            if (to.path === '/reservation/details') {
                this.init()
            }
        },
        appointmentDate: function (val, oldValue) {
            if (this.formItem.type === '' || this.formItem.process === '') {
                setTimeout(() => {
                    this.appointmentDate = ''
                }, 100)
            } else {
                let datetime = this.appointmentDate + ' ' + this.appointmentTime
                if (this.appointmentDate !== '' && this.appointmentTime !== '') {
                    this.changeAppointment(datetime);
                }
            }
        },
        appointmentTime: function (val, oldValue) {
            if (this.formItem.type === '' || this.formItem.process === '') {
                setTimeout(() => {
                    this.appointmentTime = ''
                }, 100)
            } else {
                let datetime = this.appointmentDate + ' ' + this.appointmentTime
                if (this.appointmentDate !== '' && this.appointmentTime !== '') {
                    this.changeAppointment(datetime);
                }
            }
        }
    }
}
</script>

<style>
.divClass {
    background-color: #fff;
}
</style>
